<?php
// +---------------------------------------------------------------------+
// | Author     | czc2415@qq.com    www.codeccc.cn                             |
// +---------------------------------------------------------------------+

namespace app\admin\controller;

use think\Request;

/**
 * 自动化
 * 在网址输入  域名/admin.php/ccauto/auto   生成自动生成文件
 */
class Ccauto extends AdminBase
{


    private $img_field_array;//多图片字段集合
    private $one_img_field_array;//单图片字段集合
    private $article_field_array;//文章字段集合
    private $file_field_array;//字段集合
    private $fieid_comment_array = array();//字段备注
    private $table_name ='';//表名
    public function auto(Request $request)
    {
        if (IS_POST) {
            $data = $request->param();
            if ($data['cccontroller'] != '' && $data['ccmodel'] != '' && $data['table_name'] != '') {
                dump($data);
                $this->table_name = mb_substr($data['table_name'],mb_strlen(config("database.prefix"))).'_';
                $controller = $data['cccontroller'];
                $model = $data['ccmodel'];
                //特殊字段
                $img_id_array = preg_split('/;/', $data['coneimgFieId']);
                $this->one_img_field_array = $img_id_array;
                $img_id_array = preg_split('/;/', $data['cimgFieId']);
                $this->img_field_array = $img_id_array;
                $img_id_array = preg_split('/;/', $data['carticleFieId']);
                $this->article_field_array = $img_id_array;
                $img_id_array = preg_split('/;/', $data['cfileFieId']);
                $this->file_field_array = $img_id_array;

                $this->createModel($model);
                $this->createController($controller, $model);
                $this->createLogic($controller, $model);
                $model_class = '\app\admin\model\\' . $model;
                $model_class = new $model_class;

                //html
                $this->createHtml($controller, $model_class->showFieId($data['table_name'],$this->fieid_comment_array));
                $menu_data = array();
                $menu_data['name'] = $data['table_name'];
                $menu_data['pid'] = '0';
                $menu_data['sort'] = '0';
                $menu_data['module'] = 'admin';
                $menu_data['status'] = '1';

                $aaa=\app\admin\model\Menu::where('name',$data['table_name'])->where('status',1)->find();
                if($aaa){//存在
                    for ($i = 0; $i < 6; $i++) {
                        $f = $aaa['id']+$i;
                        \app\admin\model\Menu::where('id',$f)->delete();//删除父级
                    }
                }


                //最上级
                $menu_data['url'] = 'cc'.time();
                \app\admin\model\Menu::create($menu_data);
                $pid=\app\admin\model\Menu::getLastInsID();

                //列表
                $menu_data['name'] = '列表';
                $menu_data['url'] = strtolower($controller) . '/'.$this->table_name.'lists';
                $menu_data['is_hide'] = '0';
                $menu_data['pid'] = $pid;
                \app\admin\model\Menu::create($menu_data);
                $pid2=\app\admin\model\Menu::getLastInsID();
                //编辑
                $menu_data['name'] = '编辑';
                $menu_data['url'] = strtolower($controller) . '/'.$this->table_name.'edit';
                $menu_data['is_hide'] = '1';
                $menu_data['pid'] = $pid2;
                \app\admin\model\Menu::create($menu_data);
                //删除
                $menu_data['name'] = '删除';
                $menu_data['url'] = strtolower($controller) . '/'.$this->table_name.'del';
                $menu_data['is_hide'] = '1';
                $menu_data['pid'] = $pid2;
                \app\admin\model\Menu::create($menu_data);
                //增加
                $menu_data['name'] = '新增';
                $menu_data['url'] = strtolower($controller) . '/'.$this->table_name.'add';
                $menu_data['is_hide'] = '0';
                $menu_data['pid'] = $pid;
                \app\admin\model\Menu::create($menu_data);
                //详情
                $menu_data['name'] = '详情';
                $menu_data['url'] = strtolower($controller) . '/'.$this->table_name.'detail';
                $menu_data['is_hide'] = '1';
                $menu_data['pid'] = $pid2;
                \app\admin\model\Menu::create($menu_data);



                $this->redirect('admin/index/index');
            } else {
                $this->redirect('admin/index/index');
            }
        }
        $menus = \app\admin\model\Menu::where(['url' => 'ccauto/auto'])
            ->where('status', '<>', '-1')
            ->find();
        if (!$menus) {
            $menu_data = array();
            $menu_data['name'] = '自动化创建表增删改查';
            $menu_data['pid'] = '0';
            $menu_data['sort'] = '0';
            $menu_data['module'] = 'admin';
            $menu_data['url'] = 'ccauto/auto';
            $menu_data['is_hide'] = '0';
            $menu_data['status'] = '1';
            \app\admin\model\Menu::create($menu_data);

        }
        //创建自动化文件
        $mfile = APP_PATH . 'admin/view/ccauto';
        if (!is_dir($mfile)) {
            mkdir($mfile);
        }
        $auto_file = $mfile . '/auto.html';
        if (!is_file($auto_file)) {
            $file_path = $auto_file;
            $myfile = fopen($file_path, "w") or die("Unable to open file!");
            $txt = $this->htmlAutoText();
            fwrite($myfile, $txt);
            fclose($myfile);
        }
        return $this->fetch('auto');
    }

    /**
     * 自动化文件html
     */
    public function htmlAutoText()
    {
        $text = '
        <form action="{:url()}" method="post" class="form_single">
    <p>按要求填写正确的数据可对应表自动生成增删改查</p>
    <p>控制器名称不能与模型名称一样</p>
    <div class="box">
      <div class="box-body">
        <div class="row">
          <div class="col-md-6">
            <div class="form-group">
              <label>控制器</label>
              <span>（除首字母大写外其他都小写）</span>
              <input class="form-control" name="cccontroller" placeholder="Textsone" type="text">
            </div>
          </div>
 
          <div class="col-md-6">
            <div class="form-group">
              <label>模型</label>
              <input class="form-control" name="ccmodel" placeholder="TextModelss" type="text">
            </div>
          </div>

          <div class="col-md-6">
            <div class="form-group">
              <label>完整表名</label>
              <span>（包括表前缀）</span>
              <input class="form-control" name="table_name" placeholder="cc_text_modelss" type="text">
            </div>
          </div>
          
          <div class="col-md-6">
            <div class="form-group">
              <label>单图片上传字段</label>
              <span>(多个字段用英文状态的分号隔开“;”。该功能可多图上传,图片地址：/upload/picture/xxxxxxxx)</span>
              <input class="form-control" name="coneimgFieId" placeholder="img_id" type="text">
              <!--<select name="competition" class="form-control">-->
                <!--<option value="imgs">图片上传</option>-->
              <!--</select>-->
            </div>
          </div>
            
          <div class="col-md-6">
            <div class="form-group">
              <label>多图片上传字段</label>
              <span>(该功能可多图上传,图片地址：/upload/picture/xxxxxxxx)</span>
              <input class="form-control" name="cimgFieId" placeholder="img_ids" type="text">
              <!--<select name="competition" class="form-control">-->
                <!--<option value="imgs">图片上传</option>-->
              <!--</select>-->
            </div>
          </div>
          
          <div class="col-md-6">
            <div class="form-group">
              <label>文章编辑字段</label>
              <span>(多个用英文状态的分号隔开“;”。</span>
              <input class="form-control" name="carticleFieId" placeholder="article_id" type="text">
            </div>
          </div>

          <div class="col-md-6">
            <div class="form-group">
              <label>文件上传字段</label>
              <span>(多个用英文状态的分号隔开“;”。</span>
              <input class="form-control" name="cfileFieId" placeholder="file_id" type="text">
            </div>
          </div>

        </div>
      </div>
      <div class="box-footer">
        
        <!--{include file="layout/edit_btn_group"/}-->
        <button type="submit" class="btn ladda-button" >
          <span class="ladda-label"><i class="fa fa-send"></i> 确 定</span>
        </button>
      </div>
    </div>
</form>
        ';
        return $text;
    }

    //创建html
    public function createHtml($controller_name, $field_array = array())
    {
        $controller_name = strtolower($controller_name);
        $dir = APP_PATH . '/admin/view/' . $controller_name;
        if (!is_dir($dir)) {
            mkdir($dir, 7777);
        };

        $type_arr = array($this->table_name.'lists', $this->table_name.'add', $this->table_name.'edit',$this->table_name.'detail');
        foreach ($type_arr as $type) {
            $file_path = APP_PATH . 'admin/view/' . $controller_name . "/{$type}.html";
            $myfile = fopen($file_path, "w") or die("Unable to open file!");
            $txt = $this->htmlText($type, $field_array);
            fwrite($myfile, $txt);
            fclose($myfile);
        }
    }

    //创建html的子函数
    //$type = lists     列表页
    //$type = add       新增页
    //$type = edit      编辑页
    //$type = detail      详情页
    public function htmlText($type, $field = array())
    {
        if ($type == $this->table_name.'lists') {
            return $this->htmlListsText($field);
        }
        else if ($type == $this->table_name.'add') {
            return $this->htmlAddText($field);
        }
        else if ($type == $this->table_name.'edit') {
            return $this->htmlEditText($field);
        }
        else if($type==$this->table_name.'detail'){
            return $this->htmlDetailText($field);
        }
    }

    //列表 html代码
    private function htmlListsText($field = array()){
        $tl = '';//搜索框选项
        $g = '';
        foreach ($field as $ind=>$item) {
            if (!in_array($item, $this->article_field_array)) {
                $tl .= '<option value="'.$item.'">' . $this->fieid_comment_array[$ind] . '</option>';
            }
        }
        $text = '
<div class="box">
    <div class="box-header ">
        <div class="col-md-1">
            <ob_link><a class="btn" href="{:url(\''.$this->table_name.'add\')}"><i class="fa fa-plus"></i> 新 增</a></ob_link>
            <br/>
        </div>
        <div class="col-md-3">
            <form class="form-inline" action="{:url()}" method="post">
                    <div class="form-group">
                        <select class="form-control" name="search_field" style="width: 115px">                            
                            '.$tl.'
                        </select>
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" name="search_value" value="{$search_value}">
                    </div>
                    <input type="text" value="search" name="type" hidden>
                    <button type="submit" class="btn btn-default">搜索</button>
                </form>
        </div>
    </div>

    <div class="box-body table-responsive">
        <table class="table table-bordered table-hover">
            <thead>
            <tr>';

        $v = '';
        foreach ($field as $ind=>$item) {
            if (!in_array($item, $this->article_field_array)) {
                $v .= '<th>' . $this->fieid_comment_array[$ind] . '</th>';
            }
        }
        $v .= '<th>操作</th>';
        $text .= $v;

        $text .= '
            </tr>
            </thead>
            {notempty name=\'list\'}
            <tbody>
            {volist name=\'list\' id=\'vo\'}
            <tr>';



        //中部
        foreach ($field as $ind=>$item) {
            $is_img = false;
            $is_article = false;
            $is_file = false;
            // 判断字段类型
            if (in_array($item, $this->img_field_array)) {
                $is_img = true;
            }
            if (in_array($item, $this->article_field_array)) {
                $is_article = true;
            }
            if (in_array($item, $this->file_field_array)) {
                $is_file = true;
            }


            if ($is_img) {
                $g .= '<td>
<img class="admin-list-img-size" src="{$vo.' . $item . '|get_picture_url}"/>　{:substr_count($vo["' . $item . '"],\',\')?substr_count($vo["' . $item . '"],\',\'):0; }张
</td>
';
            } else if ($is_article) {
                $g .= '
<td>{:mb_strimwidth($vo["' . $item . '"],0,18,"..."); }</td>
';
            } else if ($is_file) {
                $g .= '
<td>{$vo["' . $item . '"]?"有":"空"; }</td>
';
            } else {
                $g .= '
<td>{:mb_strimwidth($vo["' . $item . '"],0,18,"..."); }</td>
';
            }


        }



        //底部

        $g .= '
                <td class="col-md-3 text-center">
                    <ob_link><a href="{:url(\''.$this->table_name.'detail\', array(\'id\' => $vo[\'id\']))}" class="btn"><i class="fa fa-bitbucket"></i> 详 情</a></ob_link>
                    &nbsp;
                    <ob_link><a href="{:url(\''.$this->table_name.'edit\', array(\'id\' => $vo[\'id\']))}" class="btn"><i class="fa fa-edit"></i> 编 辑</a></ob_link>
                    &nbsp;                    
                    <ob_link><a class="btn confirm ajax-get" href="{:url(\''.$this->table_name.'del\', array(\'id\' => $vo[\'id\']))}"><i class="fa fa-trash-o"></i> 删 除</a></ob_link>
                </td>';
//        <!--<img class="admin-list-img-size" src="{$vo.img_id|get_picture_url}"/>-->
        $text .= $g;
        $text .= '
            </tr>
            {/volist}
            </tbody>
            {else/}
            <tbody>
            <tr class="odd">
                <td colspan="8" class="text-center" valign="top">{:config(\'empty_list_describe\')}</td>
            </tr>
            </tbody>
            {/notempty}
        </table>
    </div>
    <div class="box-footer clearfix text-center">
        {$list->render()}
    </div>

</div>
<script>
    var s = $(\'select:first\');
    var selected = \'{$search_field}\';
    for(var i=0;i<s.find(\'option\').length;i++){
        if(s.find(\'option\').eq(i).val()==selected){
            s.find(\'option\').eq(i).attr({\'selected\':selected})
        }
    }
</script>
        ';

        return $text;

    }

    //添加 html代码
    private function htmlAddText($field = array()){

        $text = '
        <form action="{:url()}" method="post" class="form_single">
    <div class="box">
      <div class="box-body">
        <div class="row">
        ';

        $g = '';
        foreach ($field as $ind=>$item) {
            $is_img = false;//多图
            $is_one_img = false;//单图
            $is_article = false;
            $is_file = false;
            // 判断字段类型
            if (in_array($item, $this->img_field_array)) {
                $is_img = true;
            }
            if (in_array($item, $this->one_img_field_array)) {
                $is_one_img = true;
            }
            if (in_array($item, $this->article_field_array)) {
                $is_article = true;
            }
            if (in_array($item, $this->file_field_array)) {
                $is_file = true;
            }


            if ($item == 'id' or $item == 'create_time' or $item == 'update_time') {
                continue;
            }
            if ($is_img) {
                $g .= '<div class="col-md-6">
                            <div class="form-group">
                              <label>' . $this->fieid_comment_array[$ind] . '</label>
                              {assign name="' . $item . '" value="$info.' . $item . '|default=\'\'" /}
                              {:widget(\'file/index\', [\'name\' => \'' . $item . '\', \'value\' => $' . $item . ', \'type\' => \'imgs\'])}
                            </div>
                          </div>' . "\n";
            }else if ($is_one_img) {
                $g .= '<div class="col-md-6">
                            <div class="form-group">
                              <label>' . $this->fieid_comment_array[$ind] . '</label>
                              {assign name="' . $item . '" value="$info.' . $item . '|default=\'\'" /}
                              {:widget(\'file/index\', [\'name\' => \'' . $item . '\', \'value\' => $' . $item . ', \'type\' => \'img\'])}
                            </div>
                          </div>' . "\n";
            } else if ($is_article) {
                $g .= '<div class="col-md-6">
                            <div class="form-group">
                              <label>' . $this->fieid_comment_array[$ind] . '</label>
                              <textarea class="form-control textarea_editor" name="' . $item . '" placeholder="请输入文章内容">{$info[\'' . $item . '\']|default=\'\'}</textarea>
                              {:widget(\'editor/index\', array(\'name\'=> \'' . $item . '\',\'value\'=> \'\'))}
                            </div>
                          </div>' . "\n";
            } else if ($is_file) {
                $g .= '<div class="col-md-6">
                            <div class="form-group">
                              <label>' . $this->fieid_comment_array[$ind] . '</label>
                              {assign name="' . $item . '" value="$info.' . $item . '|default=\'0\'" /}
                              {:widget(\'file/index\', [\'name\' => \'' . $item . '\', \'value\' => $' . $item . ', \'type\' => \'file\'])}
                            </div>
                          </div>' . "\n";
            } else {

                $g .= '<div class="col-md-6">
                            <div class="form-group">
                              <label>' . $this->fieid_comment_array[$ind] . '</label>
                              <input class="form-control" name="' . $item . '" type="text">
                            </div>
                          </div>' . "\n";

            }
        }



        $text .= $g;
        $text .= '
        </div>
      </div>
      <div class="box-footer">
        {include file="layout/edit_btn_group"/}
      </div>
    </div>
</form>
        ';
        return $text;


    }
    //编辑 html代码
    private function htmlEditText($field = array()){

        $text = '
        <form action="{:url()}" method="post" class="form_single">
    <div class="box">
      <div class="box-body">
        <div class="row">
        ';

        $g = '';
        foreach ($field as $ind=>$item) {
            $is_img = false;//多图
            $is_one_img = false;//单图
            $is_article = false;
            $is_file = false;
            // 判断字段类型
            if (in_array($item, $this->img_field_array)) {
                $is_img = true;
            }
            if (in_array($item, $this->one_img_field_array)) {
                $is_one_img = true;
            }
            if (in_array($item, $this->article_field_array)) {
                $is_article = true;
            }
            if (in_array($item, $this->file_field_array)) {
                $is_file = true;
            }

            if ($item == 'id' or $item == 'create_time' or $item == 'update_time') {
                continue;
            }
            if ($is_img) {
                $g .= '<div class="col-md-6">
                            <div class="form-group">
                              <label>' . $this->fieid_comment_array[$ind] . '</label>
                              {assign name="' . $item . '" value="$info.' . $item . '|default=\'\'" /}
                              {:widget(\'file/index\', [\'name\' => \'' . $item . '\', \'value\' => $' . $item . ', \'type\' => \'imgs\'])}
                            </div>
                          </div>' . "\n";
                // {assign name="cover_id" value="$info.cover_id|default='0'" /}
                // {:widget('file/index', ['name' => 'cover_id', 'value' => $cover_id, 'type' => 'img'])}
            }else if ($is_one_img) {
                $g .= '<div class="col-md-6">
                            <div class="form-group">
                              <label>' . $this->fieid_comment_array[$ind] . '</label>
                              {assign name="' . $item . '" value="$info.' . $item . '|default=\'\'" /}
                              {:widget(\'file/index\', [\'name\' => \'' . $item . '\', \'value\' => $' . $item . ', \'type\' => \'img\'])}
                            </div>
                          </div>' . "\n";
            }  else if ($is_article) {
                $g .= '<div class="col-md-6">
                            <div class="form-group">
                              <label>' . $this->fieid_comment_array[$ind] . '</label>
                              <textarea class="form-control textarea_editor" name="' . $item . '" placeholder="请输入文章内容">{$info[\'' . $item . '\']|default=\'\'}</textarea>
                              {:widget(\'editor/index\', array(\'name\'=> \'' . $item . '\',\'value\'=> \'\'))}
                            </div>
                          </div>' . "\n";
            } else if ($is_file) {
                $g .= '<div class="col-md-6">
                            <div class="form-group">
                              <label>' . $this->fieid_comment_array[$ind] . '</label>
                              {assign name="' . $item . '" value="$info.' . $item . '|default=\'0\'" /}
                              {:widget(\'file/index\', [\'name\' => \'' . $item . '\', \'value\' => $' . $item . ', \'type\' => \'file\'])}
                            </div>
                          </div>' . "\n";
            } else {
                $g .= '<div class="col-md-6">
                            <div class="form-group">
                              <label>' . $this->fieid_comment_array[$ind] . '</label>
                              <input class="form-control" name="' . $item . '" value="{$info[\'' . $item . '\']}" type="text">
                            </div>
                          </div>' . "\n";
            }
        }


        $text .= $g;
        $text .= '
        </div>
      </div>
      <div class="box-footer">
        <input type="hidden" name="id" value="{$info[\'id\']|default=\'0\'}"/>
        {include file="layout/edit_btn_group"/}
      </div>
    </div>
</form>
        ';

        return $text;

    }
    //详情 html代码
    private function htmlDetailText($field = array()){
        $text = '
        <form action="{:url()}" method="post" class="form_single">
    <div class="box">
      <div class="box-body">
        <div class="row">
        ';

        $g = '';
        foreach ($field as $ind=>$item) {
            $is_img = false;//多图
            $is_one_img = false;//单图
            $is_article = false;
            $is_file = false;
            // 判断字段类型
            if (in_array($item, $this->img_field_array)) {
                $is_img = true;
            }
            if (in_array($item, $this->one_img_field_array)) {
                $is_one_img = true;
            }
            if (in_array($item, $this->article_field_array)) {
                $is_article = true;
            }
            if (in_array($item, $this->file_field_array)) {
                $is_file = true;
            }

            if ($item == 'id' or $item == 'create_time' or $item == 'update_time') {
                continue;
            }
            if ($is_img) {
                $g .= '<div class="col-md-6">
                            <div class="form-group">
                              <label>' . $this->fieid_comment_array[$ind] . '</label>
                              {assign name="' . $item . '" value="$info.' . $item . '|default=\'\'" /}
                              {:widget(\'file/index\', [\'name\' => \'' . $item . '\', \'value\' => $' . $item . ', \'type\' => \'imgs\'])}
                            </div>
                          </div>' . "\n";
                // {assign name="cover_id" value="$info.cover_id|default='0'" /}
                // {:widget('file/index', ['name' => 'cover_id', 'value' => $cover_id, 'type' => 'img'])}
            }else if ($is_one_img) {
                $g .= '<div class="col-md-6">
                            <div class="form-group">
                              <label>' . $this->fieid_comment_array[$ind] . '</label>
                              {assign name="' . $item . '" value="$info.' . $item . '|default=\'\'" /}
                              {:widget(\'file/index\', [\'name\' => \'' . $item . '\', \'value\' => $' . $item . ', \'type\' => \'img\'])}
                            </div>
                          </div>' . "\n";
            } else if ($is_article) {
                $g .= '<div class="col-md-6">
                            <div class="form-group">
                              <label>' . $this->fieid_comment_array[$ind] . '</label>
                              <textarea class="form-control textarea_editor" name="' . $item . '" placeholder="请输入文章内容">{$info[\'' . $item . '\']|default=\'\'}</textarea>
                              {:widget(\'editor/index\', array(\'name\'=> \'' . $item . '\',\'value\'=> \'\'))}
                            </div>
                          </div>' . "\n";
            } else if ($is_file) {
                $g .= '<div class="col-md-6">
                            <div class="form-group">
                              <label>' . $this->fieid_comment_array[$ind] . '</label>
                              {assign name="' . $item . '" value="$info.' . $item . '|default=\'0\'" /}
                              {:widget(\'file/index\', [\'name\' => \'' . $item . '\', \'value\' => $' . $item . ', \'type\' => \'file\'])}
                            </div>
                          </div>' . "\n";
            } else {
                $g .= '<div class="col-md-6">
                            <div class="form-group">
                              <label>' . $this->fieid_comment_array[$ind] . '</label>
                              <p style="color: #a7a7a7;">{$info[\'' . $item . '\']}</p>
                            </div>
                          </div>' . "\n";
            }
        }


        $text .= $g;
        $text .= '
        </div>
      </div>
      <div class="box-footer">
<a class="btn" onclick="javascript:history.back(-1);return false;"><i class="fa fa-history"></i> 返 回</a>

        </div>
    </div>
</form>
        ';

        return $text;


    }


    /**
     * 创建模型
     * @param string $model_name
     */
    public function createModel($model_name = 'ppop')
    {
        $file_path = APP_PATH . 'admin/model/' . $model_name . '.php';
        $myfile = fopen($file_path, "w") or die("Unable to open file!");
        $txt = "<?php\n
namespace app\admin\model;\n

class $model_name extends AdminBase\n
{\n";
        $txt .= '
        
    public function showFieId($table,&$field_comment){
        $database =config("database.database"); 
        $sql = "select * from information_schema.columns where table_name = \'$table\' and table_schema = \'$database\'";
        $res=$this->query($sql);
        $f = array();//字段名
        $f_comment = array();//字段备注
        foreach ($res as $re) {
            $f[] = $re[\'COLUMN_NAME\'];
            $f_comment[] = $re[\'COLUMN_COMMENT\']!=\'\'?$re[\'COLUMN_COMMENT\']:$re[\'COLUMN_NAME\'];
        }
        $field_comment = $f_comment;
        return $f;
    }
}
';
        fwrite($myfile, $txt);
        fclose($myfile);
    }

    /**
     * 创建控制器
     * @param string $controller_name
     */
    public function createController($controller_name = 'ppop', $model_name = 'Bcf')
    {
        $file_path = APP_PATH . 'admin/controller/' . $controller_name . '.php';
        $myfile = fopen($file_path, "w") or die("Unable to open file!");
        $txt = $this->controllerText($controller_name, $model_name);

        fwrite($myfile, $txt);
        fclose($myfile);
    }

    //控制器内容
    public function controllerText($controller_name = 'Asdc', $model_name = 'Bcf')
    {
        $img_str = '';
        if (!($this->img_field_array[0] == '')) {
            foreach ($this->img_field_array as $img) {
                $img_str .= '$info["' . $img . '_array"] = str2arr($info["' . $img . '"]);' . "\n\n\t\t";
            }
        }

        $text = '<?php ' . "\n" . "
namespace app\admin\controller;
use app\admin\model\\" . "$model_name;
use think\Request;
use think\Cookie;
class " . $controller_name . ' extends AdminBase{
    /**
     * 列表
     */
    public function '.$this->table_name.'lists(Request $request)
    {
        Cookie::init([\'expire\' => 3600,\'path\'=>\'admin_'.$controller_name.'_\']);
        $type = $request->post(\'type\');
        if ($type == \'search\') {
            Cookie::set(\'search_field\', $request->post(\'search_field\'));
            Cookie::set(\'search_value\', $request->post(\'search_value\'));
        }
        $search_field = Cookie::has(\'search_field\') ? Cookie::get(\'search_field\') : \'id\';
        $search_value = Cookie::has(\'search_value\') ? Cookie::get(\'search_value\') : \'\';
        
        $lists=' . $model_name . '::where($search_field, \'like\', "%$search_value%")->order(\'create_time\',\'desc\')->paginate(20);       

        $this->assign(\'list\', $lists);
        $this->assign(\'search_value\', $search_value);
        $this->assign(\'search_field\', $search_field);
        return $this->fetch(\''.$this->table_name.'lists\');
    }
    /**
     * 增加
     */
    public function '.$this->table_name.'add()
    {

        IS_POST && $this->jump($this->logic' . $controller_name . '->'.$this->table_name.'add($this->param));

        return $this->fetch("'.$this->table_name.'add");
    }

    /**
     * 编辑
     */
    public function '.$this->table_name.'edit()
    {

        IS_POST && $this->jump($this->logic' . $controller_name . '->'.$this->table_name.'Edit($this->param));

        $info = $this->logic' . $controller_name . '->'.$this->table_name.'Info(["id" => $this->param["id"]]);
        
        ' . $img_str . '$this->assign("info", $info);
        
        return $this->fetch("'.$this->table_name.'edit");
    } 
    /**
     * 详情
     */
    public function '.$this->table_name.'detail()
    {
        $info = $this->logic' . $controller_name . '->'.$this->table_name.'Info(["id" => $this->param["id"]]);
        
        ' . $img_str . '$this->assign("info", $info);
        
        return $this->fetch("'.$this->table_name.'detail");
    }

    /**
     * 删除
     */
    public function '.$this->table_name.'del($id = 0)
    {
        return $this->jump($this->logic' . $controller_name . '->'.$this->table_name.'Del(["id" => $id]));
    }
    }
';
        return $text;
    }

    //创建logic文件
    private function createLogic($controller_name, $model_name)
    {

        $file_path = APP_PATH . 'admin/logic/' . $controller_name . '.php';
        $myfile = fopen($file_path, "w") or die("Unable to open file!");
        $txt = $this->logicText($controller_name, $model_name);

        fwrite($myfile, $txt);
        fclose($myfile);
    }

    //创建logic文件的子函数
    private function logicText($controller_name, $model_name)
    {
        $text = '<?php
namespace app\admin\logic;
use app\admin\model\\' . $model_name . ';
class ' . $controller_name . ' extends AdminBase{
        /**
     * 添加
     */
    public function '.$this->table_name.'add($data = [])
    {
        $url = url(\''.$this->table_name.'lists\');
        $data["create_time"] = time();
        $data["update_time"] = time();
        $result = ' . $model_name . '::create($data);
        return $result ? [RESULT_SUCCESS, \'添加成功\', $url] : [RESULT_ERROR, \'添加错误\'];
    }
    /**
     * 更新
     * @param array $data
     * @return array
     */
    public function '.$this->table_name.'Edit($data=[])
    {
        $url = url(\''.$this->table_name.'lists\');
        $data["update_time"] = time();
        $id = $data[\'id\'];
        unset($data[\'id\']);
        $result = ' . $model_name . '::where(\'id\',$id)->update($data);
        return $result ? [RESULT_SUCCESS, \'编辑成功\', $url] : [RESULT_ERROR, \'编辑失败\'];
    }
    /**
     * 获取信息
     */
    public function '.$this->table_name.'Info($where = [], $field = true)
    {
        $info=' . $model_name . '::get($where);
        return $info;
    }
     /**
     * 删除
     * @param $id
     * @return array
     */
    public function '.$this->table_name.'Del($id)
    {
        $url=url(\''.$this->table_name.'lists\');
        $result = ' . $model_name . '::destroy($id);
        return $result ? [RESULT_SUCCESS, \'删除成功\', $url] : [RESULT_ERROR, \'删除失败\', $url];

    }
    }
        ';
        return $text;
    }
}
